package com.example.birdfriends.controller;

import com.example.birdfriends.pojo.post.Post;
import com.example.birdfriends.pojo.post.PostFront;
import com.example.birdfriends.pojo.read.Reader;
import com.example.birdfriends.pojo.user.User;
import com.example.birdfriends.service.PostService;
import com.example.birdfriends.service.ReadService;
import com.example.birdfriends.service.UserService;
import com.example.birdfriends.utils.convert.ConvertService;
import com.example.birdfriends.utils.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.jws.soap.SOAPBinding;
import java.sql.Timestamp;
import java.util.*;

@RequestMapping("/post/read")
@RestController
public class ReadController {
    @Autowired
    ReadService readService = null;
    @Autowired
    PostService postService = null;
    @Autowired
    private ConvertService convertService = null;
    @Autowired
    private Result result = null;

    @PostMapping("/addReader")
    public Map<String, Object> addReader(@RequestBody PostFront postFront){
        Long pid = postFront.getPid(); // pid是当前帖子的id
        Long curLoginUid = postFront.getCurLoginUid();  // 当前登录用户
        String curPage = postFront.getCurPage();
        Timestamp readTime = new Timestamp(System.currentTimeMillis());

        Reader reader = new Reader();
        reader.setReadTime(readTime);
        reader.setPid(pid);
        reader.setUid(curLoginUid);

        int add = readService.addReader(reader);

        boolean success = add > 0;
        if(success){
            Post post = postService.findPostByPid(pid);
            PostFront ansPostFront = convertService.post2PostFront(post, curLoginUid, curPage);
            return result.resultMap(true, "添加读者成功", ansPostFront);
        }
        return result.resultMap(false, "添加读者失败", null);
    }

    @Autowired
    private UserService userService = null;

    @PostMapping("/queryReaders")
    public Map<String, Object> queryPostReaders(@RequestBody PostFront postFront){
        Long pid = postFront.getPid();
        List<Long> newUids = convertService.removeDuplicateUid(pid);
        boolean success = newUids != null && newUids.size() > 0;

        if (success){
            List<User> readers = new ArrayList<>();
            for(Long uid: newUids){
                User user = userService.findUserByUid(uid);
                readers.add(user);
            }
            return result.resultMap(true, "查询读者成功", readers);
        }

        return result.resultMap(false, "查询读者失败", null);
    }
}
